<template>
  <div class="page">
    <div class="handlePart">
      <el-form :inline="true" :model="form">
        <el-form-item label="关键字：">
          <el-input size="small" v-model="form.keywords" placeholder="根据角色名称模糊检索" clearable></el-input>
        </el-form-item>
        <el-form-item label="创建日期：">
          <el-date-picker size="small" v-model="date" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <!-- <el-button size="small" type="danger" icon="el-icon-delete" @click="dels">删除</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <div class="tablePart">
      <el-row :gutter="20">
        <el-col :span="18">
          <el-table :data="list" :height="'calc(100vh - 290px)'" stripe style="width: 100%"
            @selection-change="handleSelectionChange" highlight-current-row @current-change="currentChange">
            <!-- <el-table-column type="selection" width="55">
            </el-table-column> -->
            <el-table-column label="序号" type="index" align="center" width="55">
            </el-table-column>
            <el-table-column prop="roleName" label="名称" align="center"> </el-table-column>
            <el-table-column prop="remark" label="描述" align="center"> </el-table-column>
            <el-table-column label="是否启用" align="center">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="statusChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建日期" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="160">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-edit" title="编辑" @click="edit(scope.row)"></el-button>
                <!-- <el-button type="text" icon="el-icon-delete" title="删除" @click="del(scope.row)"></el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <div class="pagePart">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
              :page-sizes="[10, 20, 30, 40, 50]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-col>
        <el-col :span="6">
          <el-card shadow="never">
            <div slot="header">
              <span>功能权限分配</span>
              <el-button style="float: right;padding: 5px 8px;" size="small" type="primary" icon="el-icon-check" @click="save">保存</el-button>
            </div>
            <div style="height: calc(100vh - 325px);overflow:auto;">
              <el-tree
                :data="roleGuid ? menuList : []"
                show-checkbox
                default-expand-all
                node-key="id"
                ref="menuTree"
                highlight-current
                :props="defaultProps">
              </el-tree>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <EditDialog ref="editDialogRef" @listInit="listInit" />
  </div>
</template>
<script>
import EditDialog from './editDialog.vue';
export default {
  data() {
    return {
      form: {
        keywords: '',
        end: '',
        start: '',
        orderBy: 'sort'
      },
      date: [],
      list: [],
      page: 1,
      size: 10,
      total: 0,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      selectList: [],
      roleGuid: null,
      menuList: [],   // 全部菜单
      checkList: []
    };
  },
  mounted() {
    this.listInit();
    this.getMenuList()
    // this.$api.getDictList({page:1,size:1000})
    // this.$api.getDictDetail({dicGuid: '1391306323524675'})
  },
  methods: {
    listInit() {
      if(this.date && this.date.length){
        this.form.start = this.date[0]
        this.form.end = this.date[1]
      }else {
        this.form.start = ''
        this.form.end = ''
      }
      let params = Object.assign({},this.form,{
        size: this.size,
        page: this.page,
        orderBy: 'sort'
      })
      this.$api.getRoleManageList(params).then((res) => {
        if(res && res.code == 200){
          let data = res.data || {}
          this.total = data.total || 0
          data.list.forEach(l => {
            l.createTime = l.createTime ? this.$util.dateFunction(l.createTime) : ''
          })
          this.list = data.list || []
        }
      })
    },
    // 获取全部菜单
    getMenuList(){
      this.$api.getMenuManageList({ orderBy: 'sort' }).then(res => {
        if(res && res.code == 200){
          let data = res.data || []
          let list = this.getMenuStatusList(data)
          console.log(list)
          this.menuList = list
        }
      })
    },
    // 返回status = 1 的菜单
    getMenuStatusList(list){
      list = list.filter(l => l.status == 1)
      list.map(item => {
        if (item.children && item.children.length > 0) {
          this.getMenuStatusList(item.children)
        }
      })
      return list
    },
    // 查询
    search(){
      this.page = 1
      this.listInit()
    },
    // 新增
    add() {
      this.$refs.editDialogRef.showModal('add');
    },
    // 编辑
    edit(row) {
      this.$refs.editDialogRef.showModal('edit', row);
    },
    // 查看
    view(row) {
      this.$refs.editDialogRef.showModal('view', row);
    },
    // 删除
    del(row){
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.delRoleManage([row.sysRoleId]).then(res => {
            if(res && res.code == 200){
              this.$notify.success({
            title: '成功',
                message: '删除成功!'
              });
              this.listInit()
            }
          })
        }).catch(() => {});
    },
    // 批量删除
    dels(){
      if(this.selectList.length == 0){
        this.$notify.warning({
          title: '警告',
          message: '请至少选择一条数据！'
        });
        return
      }
      let ids = []
      this.selectList.forEach(l => {
        ids.push(l.sysRoleId)
      })
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.delRoleManage(ids).then(res => {
            if(res && res.code == 200){
              this.$notify.success({
            title: '成功',
                message: '删除成功!'
              });
              this.listInit()
            }
          })
        }).catch(() => {});
    },
    // 是否启用
    statusChange(row){
      let params = {
        id: row.sysRoleId,
        status: row.status
      }
      this.$api.changeStatusRoleManage(params).then(res => {
        if(res && res.code == 200){
          this.$notify.success({
            title: '成功',
            message: '修改成功!'
          });
          this.listInit()
        }
      })
    },
    // 多选
    handleSelectionChange(val) {
      this.selectList = val;
    },
    // 点击选择数据展示权限菜单
    currentChange(val){
      // console.log(val)
      this.roleGuid = val ? val.roleGuid : this.roleGuid
      this.$api.getRoleMenuTree({ roleGuid: this.roleGuid }).then(res => {
        if(res && res.code == 200){
          let data = res.data || []
          let list = this.getSelectLastList(data,[])
          this.$refs.menuTree.setCheckedKeys(list)
        }
      })
    },
    // 返回最后一级数据 组成数组
    getSelectLastList(list,data){
      list.map(item => {
        if (item.children && item.children.length > 0) {
          this.getSelectLastList(item.children,data)
        }else {
          data.push(item.id);
        }
      })
      return data
    },
    // 设置角色权限
    save(){
      console.log()
      let ids = this.$refs.menuTree.getCheckedKeys()
      let idss = this.$refs.menuTree.getHalfCheckedKeys()
      let params = {
        menuGuids: [...ids,...idss],
        roleGuid: this.roleGuid
      }
      this.$api.setRoleMenu(params).then(res => {
        if(res && res.code == 200){
          this.$notify.success({
            title: '成功',
            message: '设置成功!'
          });
        }
      })
    },
    // size change
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.listInit();
    },
    // page change
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.listInit();
    },
  },
  components: { EditDialog }
};
</script>
